'''
@Author: your name
@Date: 2020-03-02 09:38:17
@LastEditTime: 2020-03-03 10:53:15
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: /permcomp/comparison/models.py
'''
from django.db import models


class AndroidPermissionsManager(models.Manager):
    """AndroidPermissionsManager"""

    def fetch_permission_list(self, perms):
        permission_set = set()
        print(perms)
        for perm in perms:
            if not perm or "." not in perm:
                continue
            
            permissions = super().all()
            permission = permissions.filter(en_name=perm).first()
            if not permission and "android" in perm:
                new_perm = AndroidPermissions(en_name=perm)
                new_perm.save()
                print(new_perm.level)
                permission_set.add(new_perm)
            elif permission:
                permission_set.add(permission)
        return permission_set

    def fetch_valid_permission_list(self, perms):
        valid_perm_set = set()
        permission_set = self.fetch_permission_list(perms)
        return set(filter(lambda x: x.level >= 2, permission_set))


class AndroidPermissions(models.Model):
    """This model contains all the permissions of android"""
    PERM_LEVEL = (
        (0, 'UNKNOWN'),
        (1, 'LOW'),
        (2, 'MEDIUM'),
        (4, 'HIGH')
    )

    en_name = models.CharField(max_length=255, unique=True,
                                verbose_name='权限英文名称',
                                help_text='录入类似于 android. 的全新信息')
    zh_name = models.CharField(max_length=255, default='其它权限',
                                verbose_name='权限中文名称',
                                help_text='录入权限对应的中文解释')
    level = models.SmallIntegerField(choices=PERM_LEVEL, default=0, verbose_name='权限等级')
    alias = models.CharField(max_length=255, blank=True, null=True,
                                verbose_name='权限别名',
                                help_text='用以存储权限中文名称的别名，方便在权限描述文本中查找')

    add_time = models.TimeField(auto_now=True, verbose_name='权限信息添加时间')

    objects = AndroidPermissionsManager()

    def __str__(self):
        level_name = self.get_level_display()
        return f"{self.en_name}[{level_name}]"

    def __repr__(self):
        return self.__str__()

    class Meta:
        ordering = ['en_name']
        verbose_name = 'Android 权限信息'
    
